<template>
  <!-- 面包屑 -->
  <Breadcrumb />
  <el-button type="primary" @click="setFlag">添加套装</el-button>
  <el-table :data="shopList.slice((currentPage4-1)*pageSize4,currentPage4*pageSize4)" style="width: 100%">
    <el-table-column prop="name" label="套装名称" width="180" />
    <el-table-column prop="describe" label="套装描述" width="180" />
    <el-table-column label="套装图片" width="200px">
      <template #default="scope">
        <div class="demo-image__preview">
          <el-image
            style="width: 100px; height: 100px"
            :src="scope.row.img_path"
            :zoom-rate="1.2"
            :max-scale="7"
            :min-scale="0.2"
            :initial-index="4"
            fit="cover"
          />
        </div>
      </template>
    </el-table-column>
    <el-table-column prop="price" label="价格" width="180" />
    <el-table-column prop="number" label="库存" width="180" />
    <el-table-column prop="market" label="市场价" width="180" />
    <el-table-column label="操作">
      <template #default="scope">
        <el-button
          size="small"
          link
          type="primary"
          @click="handleEdit(scope.$index, scope.row)"
        >
          编辑
        </el-button>
        <el-popconfirm
          title="你确定要删除吗?"
          confirm-button-text="是"
          cancel-button-text="否"
          @confirm="confirmEvent(scope.row)"
          @cancel="cancelEvent"
        >
          <template #reference>
            <el-button size="small" type="danger" link>删除</el-button>
          </template>
        </el-popconfirm>
      </template>
    </el-table-column>
  </el-table>
  <!-- 分页 -->
  <!-- 分页 -->
  <div class="demo-pagination-block">
    <el-pagination
      v-model:current-page="currentPage4"
      v-model:page-size="pageSize4"
      :small="small"
      :disabled="disabled"
      :background="background"
      layout=" prev, pager, next, jumper"
      :total="shopList.length"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
  <!-- 对话弹框 -->
  <el-dialog
    v-model="flag"
    :title="flags ? '添加商品' : '编辑商品'"
    :show-close="false"
    width="800"
  >
    <el-form
      style="max-width: 600px"
      :model="forms"
      label-width="auto"
      class="demo-ruleForm"
      :size="formSize"
      status-icon
    >
      <el-form-item label="套装分类" prop="category">
        <el-select v-model="forms.category_id" placeholder="请选择套装分类">
          <el-option
            v-for="item in categoryList"
            :key="item.id"
            :label="item.title"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="套装名称" prop="name">
        <el-input v-model="forms.name" placeholder="请输入套装名称" />
      </el-form-item>
      <el-form-item label="套装描述" prop="describe">
        <el-input v-model="forms.describe" placeholder="请输入套装描述" />
      </el-form-item>
      <el-form-item label="图片" name="image">
        <el-upload
          class="avatar-uploader"
          @change="uploadfil"
          :show-file-list="false"
          list-type="picture-card"
        >
          <img v-if="forms.img_path" :src="forms.img_path" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="价格" prop="price">
        <el-input v-model="forms.price" placeholder="请输入价格" />
      </el-form-item>
      <el-form-item label="市场价" prop="marketPrice">
        <el-input v-model="forms.market" placeholder="请输入市场价" />
      </el-form-item>
      <el-form-item label="库存" prop="inventory">
        <el-input v-model="forms.number" placeholder="请输入库存" />
      </el-form-item>
      <el-form-item label="虚拟销量" prop="detail">
        <el-input v-model="forms.sales_volume" placeholder="请输入虚拟销量" />
      </el-form-item>
      <!-- 富文本 -->
      <el-form-item label="详情(富文本)" prop="virtual">
        <QuillEditor
          style="width: 100%; height: 300px"
          contentType="html"
          toolbar="full"
          ref="quillRef"
          v-model:content="forms.content"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          :plain="true"
          v-if="flags"
          type="primary"
          @click="submitForm(ruleFormRef)"
        >
          确定
        </el-button>
        <el-button
          :plain="true"
          v-else
          type="primary"
          @click="updateForm(ruleFormRef)"
        >
          确定
        </el-button>
        <el-button @click="resetForm(ruleFormRef)">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, toRefs, onMounted } from "vue";
import { Plus } from "@element-plus/icons-vue";
import Breadcrumb from "../../components/bread/Breadcrumb.vue";
import {
  getShopListAPI,
  addShopAPI,
  delShopAPI,
  getBackShopAPI,
  updateAPI,
  getSuitCategoryAPI,
} from "../../api/suit";

// 分页
const currentPage4 = ref(1)
const pageSize4 = ref(2)
const small = ref(false)
const background = ref(false)
const disabled = ref(false)
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
}
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`)
}

onMounted(async () => {
  getShopListDate();
  getCategory();
});

// 刷新列表
const render = () => {
  getShopListDate();
};

const getShopListDate = async () => {
  //获取列表数据
  let res = await getShopListAPI();

  shopList.value = Object.values(res.data.data);
};

// 获取分类
const getCategory = async () => {
  let ress = await getSuitCategoryAPI();
  categoryList.value = Object.values(ress.data.data);
  console.log(categoryList.value);
};

const shopList = ref([]);
const categoryList = ref([]);

const content = ref();
const flag = ref(false); //控制弹窗显隐
const flags = ref(true); //控制添加、修改
const oid = ref(0);
const forms = ref({
  category_id: "",
  name: "", //套装名称
  describe: "", //套装描述
  img_path: "",
  price: "", //价格
  number: "", //库存
  market: "", //市场价
  sales_volume: "", //虚拟销量
  content: "", //详情富文本
});
const form = ref([]);
// 监听富文本

// 图片上传
let imageUrl = ref("");
let uploadfil = async (files) => {
  let fileObj = files.raw;
  forms.value.img_path = fileObj;

  const reader = new FileReader();
  reader.onload = () => {
    imageUrl.value = reader.result as string;
    forms.value.img_path = reader.result as string;
  };
  reader.readAsDataURL(fileObj);
};

// 点击添加按钮
const setFlag = () => {
  flags.value = true; //控制标题等主题为添加
  flag.value = true; //控制弹窗显示
  reforms();
  forms.value.content = " ";
};
// 添加弹窗确定
const submitForm = async (formEl) => {
  flag.value = false; //控制弹窗隐藏
  let res = await addShopAPI(forms.value);
  if (res) {
    ElMessage({
      message: "添加成功",
      type: "success",
    });
  }
  render();
  console.log(forms.value);
};
// 点击编辑按钮
const handleEdit = async (index, row) => {
  flags.value = false; //控制标题等主题为修改
  flag.value = true; //控制弹窗显示
  oid.value = row.id;
  // 回显数据
  let res = await getBackShopAPI(row.id);
  forms.value = res.data.data;
  console.log(res.data.data);
};
// 编辑弹窗确定
const updateForm = async (formEl) => {
  flag.value = false; //控制弹窗隐藏
  let res = await updateAPI(oid.value, forms.value);
  if (res) {
    ElMessage({
      message: "编辑成功",
      type: "success",
    });
  }
  render();
};
// 添加/编辑弹窗取消
const resetForm = (formEl) => {
  flag.value = false; //控制弹窗隐藏
};
// 删除套装商品
const confirmEvent = async (row) => {
  //点击确定删除
  let res = await delShopAPI(row.id);
  if (res) {
    ElMessage({
      message: "删除成功",
      type: "success",
    });
  }
  render();
};
const cancelEvent = () => {
  //点击取消不删除
  console.log("cancel!");
};
// 数据回显归空
const reforms = () => {
  forms.value = {
    category_id: "",
    name: "", //套装名称
    describe: "", //套装描述
    img_path: "",
    price: "", //价格
    number: "", //库存
    market: "", //市场价
    sales_volume: "", //虚拟销量
    content: "", //详情富文本
  };
};
</script>
<style scoped lang="less">
.avatar {
  width: 100%;
  height: 100%;
  border-radius: 8px;
}
</style>